package com.xuan.yubi.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.util.Scanner;

public class TopicConsumer {

    private static final String EXCHANGE_NAME = "topic-exchange";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        Connection connection = connectionFactory.newConnection();
        Channel[] channels = new Channel[2];
        String[] queueNames = new String[2];
        Scanner in = new Scanner(System.in);


        for (int i = 0; i < 2; i++) {
            channels[i] = connection.createChannel();
            // 声明交换机名称和类型
            channels[i].exchangeDeclare(EXCHANGE_NAME, "topic");
            // 声明一个随机名称的消息队列，当消费者不再接收消息时自动销毁
            queueNames[i] = channels[i].queueDeclare("topicQ" + (i + 1), true, false, false, null).getQueue();
            System.out.println("输入当前消息队列要绑定的路由键:");
            System.out.println("输入 \"99999\" 结束绑定");
            while (in.hasNext()) {
                String routingKey = in.next();
                if ("99999".equals(routingKey)) break;
                channels[i].queueBind(queueNames[i], EXCHANGE_NAME, routingKey);
            }
        }

        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        // 接收到消息时的处理逻辑
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            try {
                Thread.sleep(10000);
                System.out.println(" [x] Received '" + message + "'");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };

        // 开始监听消息
        for (int i = 0; i < 2; i++) {
            channels[i].basicConsume(queueNames[i], true, deliverCallback, consumerTag -> {});
        }
    }

}